﻿using LiteLauncher.WIndow_Form;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using MessageBox = System.Windows.MessageBox;
using Path = System.IO.Path;
using System.IO.Compression;

namespace LiteLauncher.Pages
{
    /// <summary>
    /// DownloadPage.xaml 的交互逻辑
    /// </summary>
    public partial class DownloadPage : Page
    {
        private readonly string UserAgent = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
        private readonly string JAVA8_86_URL = "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/8/jdk/x32/windows/OpenJDK8U-jdk_x86-32_windows_hotspot_8u442b06.msi";
        private readonly string JAVA8_64_URL = "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/8/jdk/x64/windows/OpenJDK8U-jdk_x64_windows_hotspot_8u442b06.msi";
        private readonly string JAVA17_86_URL = "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jdk/x32/windows/OpenJDK17U-jdk_x86-32_windows_hotspot_17.0.14_7.msi";
        private readonly string JAVA17_64_URL = "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jdk/x64/windows/OpenJDK17U-jdk_x64_windows_hotspot_17.0.14_7.msi";
        private readonly string JAVA21_64_URL = "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/21/jdk/x64/windows/OpenJDK21U-jdk_x64_windows_hotspot_21.0.6_7.msi";

        private List<Item> releaseVersion_List = new List<Item>();
        private List<Item> snapshotVersion_List = new List<Item>();
        private List<Item> old_alphaVersion_List = new List<Item>();
        public DownloadPage()
        {
            InitializeComponent();
            LoadMinecRaft();
        }
        private async void LoadMinecRaft()
        {
            string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36";
            string MC_URL = "https://launchermeta.mojang.com/mc/game/version_manifest.json";



            using (HttpClient client = new HttpClient())
            {
                try
                {
                    client.DefaultRequestHeaders.Add("User-Agent", UserAgent);
                    string json = await client.GetStringAsync(new Uri(MC_URL));
                    JsonDocument doc = JsonDocument.Parse(json);

                    foreach (var element in doc.RootElement.GetProperty("versions").EnumerateArray())
                    {
                        var item = new Item
                        {
                            Id = element.GetProperty("id").GetString(),
                            Type = element.GetProperty("type").GetString(),
                            Url = element.GetProperty("url").GetString(),
                            Time = DateTime.Parse(element.GetProperty("time").GetString()),
                            ReleaseTime = DateTime.Parse(element.GetProperty("releaseTime").GetString())
                        };

                        switch (item.Type)
                        {
                            case "release":
                                releaseVersion_List.Add(item);
                                break;
                            case "snapshot":
                                snapshotVersion_List.Add(item);
                                break;
                            case "old_alpha":
                                old_alphaVersion_List.Add(item);
                                break;
                        }
                    }
                    // 更新UI
                    UpdateUIText(releaseVersion_List, snapshotVersion_List, old_alphaVersion_List);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("获取版本信息失败！" + ex.Message);
                }
            }
        }

        private void UpdateUIText(List<Item> releaseList, List<Item> snapshotList, List<Item> oldAlphaList)
        {
            // 绑定数据到对应的 ListView
            release_List.ItemsSource = releaseList;
            snapshot_List.ItemsSource = snapshotList;
            old_alpha_List.ItemsSource = oldAlphaList;
        }



        private async void InstallJAVA8_X86_Click(object sender, RoutedEventArgs e)
        {
            string JAVAName = "JAVA 8 32位";
            //禁用按钮
            JAVA8_86_Button.IsEnabled = false;
            string FileName = "JAVA_8_86.msi";      // 文件名
            string tempDir = Path.Combine(Path.GetTempPath(), "MCSharep_Downloads");// 创建临时目录
            string FilePath = Path.Combine(tempDir, FileName);// 创建临时文件路径

            // 尝试下载文件
            try
            {
                // 创建临时目录
                Directory.CreateDirectory(tempDir);
                using (var client = new WebClient())
                {
                    client.Headers.Add("User-Agent", UserAgent);
                    await client.DownloadFileTaskAsync(new Uri(JAVA8_86_URL), FilePath);
                    MessageBox.Show("下载完成，开始安装...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                await Silent_installation(FilePath, JAVAName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败！" + ex.Message);
            }
            finally
            {
                JAVA8_86_Button.IsEnabled = true;
            }
        }

        private async void InstallJAVA8_X64_Click(object sender, RoutedEventArgs e)
        {
            string JAVAName = "JAVA 8 64位";
            //禁用按钮
            JAVA8_X64_Button.IsEnabled = false;
            string FileName = "JAVA_8_64.msi";      // 文件名
            string tempDir = Path.Combine(Path.GetTempPath(), "MCSharep_Downloads");// 创建临时目录
            string FilePath = Path.Combine(tempDir, FileName);// 创建临时文件路径

            // 尝试下载文件
            try
            {
                // 创建临时目录
                Directory.CreateDirectory(tempDir);
                using (var client = new WebClient())
                {
                    client.Headers.Add("User-Agent", UserAgent);
                    await client.DownloadFileTaskAsync(new Uri(JAVA8_64_URL), FilePath);
                    MessageBox.Show("下载完成，开始安装...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                await Silent_installation(FilePath, JAVAName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败！" + ex.Message);
            }
            finally
            {
                JAVA8_X64_Button.IsEnabled = true;
            }
        }
        private async void InstallJAVA17_X86_Click(object sender, RoutedEventArgs e)
        {
            string JAVAName = "JAVA 17 32位";
            //禁用按钮
            JAVA17_X86_Button.IsEnabled = false;
            string FileName = "JAVA_17_64.msi";      // 文件名
            string tempDir = Path.Combine(Path.GetTempPath(), "MCSharep_Downloads");// 创建临时目录
            string FilePath = Path.Combine(tempDir, FileName);// 创建临时文件路径

            // 尝试下载文件
            try
            {
                // 创建临时目录
                Directory.CreateDirectory(tempDir);
                using (var client = new WebClient())
                {
                    client.Headers.Add("User-Agent", UserAgent);
                    await client.DownloadFileTaskAsync(new Uri(JAVA17_86_URL), FilePath);
                    MessageBox.Show("下载完成，开始安装...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                await Silent_installation(FilePath, JAVAName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败！" + ex.Message);
            }
            finally
            {
                JAVA17_X86_Button.IsEnabled = true;
            }
        }
        private async void InstallJAVA17_X64_Click(object sender, RoutedEventArgs e)
        {
            string JAVAName = "JAVA 17 64位";
            //禁用按钮
            JAVA17_X64_Button.IsEnabled = false;
            string FileName = "JAVA_17_64.msi";      // 文件名
            string tempDir = Path.Combine(Path.GetTempPath(), "MCSharep_Downloads");// 创建临时目录
            string FilePath = Path.Combine(tempDir, FileName);// 创建临时文件路径

            // 尝试下载文件
            try
            {
                // 创建临时目录
                Directory.CreateDirectory(tempDir);
                using (var client = new WebClient())
                {
                    client.Headers.Add("User-Agent", UserAgent);
                    await client.DownloadFileTaskAsync(new Uri(JAVA17_64_URL), FilePath);
                    MessageBox.Show("下载完成，开始安装...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                await Silent_installation(FilePath, JAVAName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败！" + ex.Message);
            }
            finally
            {
                JAVA17_X64_Button.IsEnabled = true;
            }
        }
        private async void InstallJAVA21_X64_Click(object sender, RoutedEventArgs e)
        {
            string JAVAName = "JAVA 21 64位";
            //禁用按钮
            JAVA21_X64_Button.IsEnabled = false;
            string FileName = "JAVA_21_64.msi";      // 文件名
            string tempDir = Path.Combine(Path.GetTempPath(), "MCSharep_Downloads");// 创建临时目录
            string FilePath = Path.Combine(tempDir, FileName);// 创建临时文件路径

            // 尝试下载文件
            try
            {
                // 创建临时目录
                Directory.CreateDirectory(tempDir);
                using (var client = new WebClient())
                {
                    client.Headers.Add("User-Agent", UserAgent);
                    await client.DownloadFileTaskAsync(new Uri(JAVA21_64_URL), FilePath);
                    MessageBox.Show("下载完成，开始安装...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                await Silent_installation(FilePath, JAVAName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载失败！" + ex.Message);
            }
            finally
            {
                JAVA21_X64_Button.IsEnabled = true;
            }
        }
        private async Task Silent_installation(string FilePath, string JAVAName)
        {
            // 静默安装
            var installProcess = new System.Diagnostics.Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "msiexec",
                    Arguments = $"/i \"{FilePath}\" /qn /norestart",
                    Verb = "runas", // 请求管理员权限
                    UseShellExecute = true,
                    CreateNoWindow = true
                }
            };
            installProcess.Start();
            await Task.Run(() => installProcess.WaitForExit());

            if (installProcess.ExitCode == 0)
            {
                MessageBox.Show($"{JAVAName}安装成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                File.Delete(FilePath); // 清理安装包
            }
            else
            {
                throw new Exception($"安装失败，退出代码：{installProcess.ExitCode}");
            }
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            releaseVersion_List.Clear();
            snapshotVersion_List.Clear();
            old_alphaVersion_List.Clear();
            LoadMinecRaft();
        }

        private void VersionTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            // 确保只能单选
            if (e.NewValue is TreeViewItem newItem)
            {
                newItem.IsSelected = true;
                // 取消其他项的选择状态
                foreach (var item in versionTree.Items)
                {
                    if (item is TreeViewItem treeItem && treeItem != newItem)
                    {
                        treeItem.IsSelected = false;
                    }
                }
            }
        }

        private async void Minecraft_Install_Button_Click(object sender, RoutedEventArgs e)
        {
            // 获取每个 ListView 中选中的项
            var selectedRelease = release_List.SelectedItem as Item;
            var selectedSnapshot = snapshot_List.SelectedItem as Item;
            var selectedOldAlpha = old_alpha_List.SelectedItem as Item;

            string installURL;
            string installVersion;
            string msg;

            // 检查每个 ListView 中是否有选中的项，并设置相应的信息
            if (selectedRelease != null)
            {
                installURL = selectedRelease.Url;
                installVersion = "正式版" + selectedRelease.Id;
                msg = $"ID: {selectedRelease.Id}\n" +
                      $"Type: {selectedRelease.Type}\n" +
                      $"Url: {selectedRelease.Url}\n" +
                      $"Time: {selectedRelease.Time:yyyy-MM-dd HH:mm:ss}\n" +
                      $"Release Time: {selectedRelease.ReleaseTime:yyyy-MM-dd HH:mm:ss}";
            }
            else if (selectedSnapshot != null)
            {
                installURL = selectedSnapshot.Url;
                installVersion = "快照版" + selectedSnapshot.Id;
                msg = $"ID: {selectedSnapshot.Id}\n" +
                      $"Type: {selectedSnapshot.Type}\n" +
                      $"Url: {selectedSnapshot.Url}\n" +
                      $"Time: {selectedSnapshot.Time:yyyy-MM-dd HH:mm:ss}\n" +
                      $"Release Time: {selectedSnapshot.ReleaseTime:yyyy-MM-dd HH:mm:ss}";
            }
            else if (selectedOldAlpha != null)
            {
                installURL = selectedOldAlpha.Url;
                installVersion = "旧版本" + selectedOldAlpha.Id;
                msg = $"ID: {selectedOldAlpha.Id}\n" +
                      $"Type: {selectedOldAlpha.Type}\n" +
                      $"Url: {selectedOldAlpha.Url}\n" +
                      $"Time: {selectedOldAlpha.Time:yyyy-MM-dd HH:mm:ss}\n" +
                      $"Release Time: {selectedOldAlpha.ReleaseTime:yyyy-MM-dd HH:mm:ss}";
            }
            else
            {
                MessageBox.Show("请先选择一个版本！");
                return;
            }

            // 创建并显示安装信息窗口
            Install_information_window installInformationWindow = new Install_information_window($"正在安装 {installVersion}", msg);
            installInformationWindow.Show();


            try
            {
                string minecraftDir = Path.Combine(Environment.GetFolderPath(
                    Environment.SpecialFolder.ApplicationData), ".minecraft");

                // 下载版本元数据
                string versionJson;
                using (var client = new WebClient())
                {
                    versionJson = await client.DownloadStringTaskAsync(installURL);
                }

                dynamic versionData = JsonConvert.DeserializeObject(versionJson);
                string versionId = versionData.id.ToString();

                // 创建版本目录
                string versionDir = Path.Combine(minecraftDir, "versions", versionId);
                Directory.CreateDirectory(versionDir);

                // 保存版本json
                File.WriteAllText(Path.Combine(versionDir, $"{versionId}.json"), versionJson);

                // 下载客户端jar
                installInformationWindow.AppendLog("\n开始下载客户端...");
                await DownloadFile(
                    versionData.downloads.client.url.ToString(),
                    Path.Combine(versionDir, $"{versionId}.jar"),
                    versionData.downloads.client.sha1.ToString()
                );

                // 处理资源索引
                installInformationWindow.AppendLog("\n下载资源索引...");
                string assetsDir = Path.Combine(minecraftDir, "assets");
                Directory.CreateDirectory(assetsDir);
                await DownloadFile(
                    versionData.assetIndex.url.ToString(),
                    Path.Combine(assetsDir, "indexes", $"{versionData.assetIndex.id}.json"),
                    versionData.assetIndex.sha1.ToString()
                );

                // 处理依赖库
                installInformationWindow.AppendLog("\n开始下载依赖库...");
                foreach (var library in versionData.libraries)
                {
                    if (!IsLibraryAllowed(library)) continue;

                    // 下载主库文件
                    if (library.downloads?.artifact != null)
                    {
                        var artifact = library.downloads.artifact;
                        string libPath = Path.Combine(minecraftDir, "libraries", artifact.path.ToString());
                        await DownloadFile(artifact.url.ToString(), libPath, artifact.sha1.ToString());
                    }

                    // 处理Windows原生文件
                    if (library.natives?.windows != null &&
                        library.downloads?.classifiers != null &&
                        library.downloads.classifiers[library.natives.windows.ToString()] != null)
                    {
                        var native = library.downloads.classifiers[library.natives.windows.ToString()];
                        string nativePath = Path.Combine(minecraftDir, "libraries", native.path.ToString());
                        await DownloadFile(native.url.ToString(), nativePath, native.sha1.ToString());

                        // 解压原生文件
                        string extractDir = Path.Combine(versionDir, "natives");
                        Directory.CreateDirectory(extractDir);
                        var archive = ZipFile.OpenRead(nativePath);
                        foreach (var entry in archive.Entries)
                        {
                            if (entry.FullName.EndsWith(".dll") || entry.FullName.EndsWith(".so"))
                            {
                                string extractPath = Path.Combine(extractDir, entry.Name);
                                entry.ExtractToFile(extractPath, overwrite: true);
                            }
                        }
                    }
                }

                installInformationWindow.AppendLog("\n下载完成！");
            }
            catch (Exception ex)
            {
                installInformationWindow.AppendLog($"\n错误: {ex.Message}");
            }


        }
        private async Task DownloadFile(string url, string path, string expectedSha1)
        {
            // 创建目录结构
            Directory.CreateDirectory(Path.GetDirectoryName(path));

            // 校验已存在文件
            if (File.Exists(path))
            {
                var stream = File.OpenRead(path);
                var sha1 = BitConverter.ToString(SHA1.Create().ComputeHash(stream)).Replace("-", "").ToLower();
                if (sha1 == expectedSha1) return;
            }

            // 下载文件
            var client = new WebClient();
            await client.DownloadFileTaskAsync(new Uri(url), path);

            // 验证下载
            var verifyStream = File.OpenRead(path);
            var actualSha1 = BitConverter.ToString(SHA1.Create().ComputeHash(verifyStream)).Replace("-", "").ToLower();
            if (actualSha1 != expectedSha1) throw new Exception($"文件校验失败：{Path.GetFileName(path)}");
        }

        private bool IsLibraryAllowed(dynamic library)
        {
            if (library.rules == null) return true;

            bool allowed = true;
            foreach (var rule in library.rules)
            {
                if (rule.os?.name?.ToString() == "windows")
                {
                    allowed = rule.action.ToString() == "allow";
                }
                else if (rule.os?.name != null) // 其他系统规则
                {
                    if (rule.action.ToString() == "allow") allowed = false;
                }
            }
            return allowed;
        }

    }

    public class Item
    {
        public string Id { get; set; }
        public string Type { get; set; }
        public string Url { get; set; }
        public DateTime Time { get; set; }
        public DateTime ReleaseTime { get; set; }
    }
}